package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录功能
     *
     * @param session
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpSession session, @RequestBody Employee employee) {
        //1.获得前端传过来的密码
        String password = employee.getPassword();
        //2.对前端获得的密码进行加密
        password = DigestUtils.md5DigestAsHex(password.getBytes()); // 加密的参数是字节数组

        // 3.根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername()); // 查询数据库里的用户名和前端传来的用户名是否一致
        Employee emp = employeeService.getOne(queryWrapper);
//        getOne是mybatis-plus的一个方法，用来获取一条数据，如果取得多条数据会报错，要么换其他方法，要么只选择其中一条，在条件构造器Wrapper结尾加上.last(“limit 1”)即可只选一条
        // 4.如果数据库用户名为空登录失败
        if (emp == null) {
            return R.error("登录失败！");
        }
        //5
        if (!emp.getPassword().equals(password)) {
            return R.error("登录失败！");
        }
        //6
        if (emp.getStatus() == 0) {
            return R.error("账号已经禁用");
        }

        //7.保存到session中
        session.setAttribute("employee", emp.getId());
        return R.success(emp);

    }

    /**
     * 退出功能
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 添加员工
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 分页
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> paging(int page, int pageSize, String name) {
        Page pageI = new Page(page, pageSize);
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 给请输入员工姓名模糊查询
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        // 根据传创建的时间递减排序
        lambdaQueryWrapper.orderByDesc(Employee::getUpdateTime);

        employeeService.page(pageI, lambdaQueryWrapper);

        return R.success(pageI);
    }

    /**
     * 根据id修改员工信息 ，启用和禁用
     *
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
          log.info("修改员工信息开始执行。。。。。。。。");
          //查看当前执行线程的id
//          long id = Thread.currentThread().getId();
//          log.info("执行线程是:{}",id);

//        Long empId = (Long)request.getSession().getAttribute("employee");
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empId);
          employeeService.updateById(employee);

        return R.success("员工信息修改成功");
    }

    /**
     * 编辑员工信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查到对用的员工信息！");
    }


}
